﻿using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using FBEntities.FBObjects;
using FBEntities.FBObjects.User;
using Newtonsoft.Json.Linq;
using XDAFacebook;
using XFControls.Utils;
using XFItemControls.XFPanels.XFPanelItems;

namespace XFControls.XFPanels.XFPanelItems
{
    public enum XFItemProfileHeadSelectedType
    {
        Picture,
        Status
    }

    public class XFItemProfileHead : XFItemBase
    {
        private int _height;
        private int _imageHeight = 128;
        private int _imageWidth = 128;
        private XFItemProfileHeadSelectedType _selected;
        private string _status;
        private FBPerson _user;
        private UpdateEventHandler _userUpdateEvent;
        private WebDownloaderWrapper _statusWrapper;

        public XFItemProfileHead()
        {
            _height = -1;
            Style = new XFItemStyle
                        {
                            TextFont = new Font(FontFamily.GenericSansSerif, 9, FontStyle.Regular),
                            Padding = 10,
                            BackgroundColor = Color.RoyalBlue,
                            TextColor = Color.White,
                            SelectedTextColor = Color.Black
                        };

            ItemType = XFItemType.Display;
        }

        public FBPerson User
        {
            get { return _user; }
            set
            {
                _user = value;

                if (value.id == XFItemControlUtils.Me.Me.id)
                    ItemType = XFItemType.Clickable;
                else
                    ItemType = XFItemType.Display;

                if (_userUpdateEvent == null)
                    _userUpdateEvent = (o, e) =>
                     {
                         ResetHeight();

                         if (!Parent.IsDisposed)
                             Parent.Damage();
                     };

                _user.Updated += _userUpdateEvent;

                _statusWrapper = User.Statuses.Parse(User.id);
                _statusWrapper.GetResults += StatusWrapperGetResults;
                _statusWrapper.BeginDownload();
            }
        }

        public override int GetHeight()
        {
            if (_height > 0)
                return _height;

            if (User == null)
                return (_height = _imageHeight + Style.PaddingTop);

            int width = GetWidth();
            if (User.Statuses.data.Count == 0 || string.IsNullOrEmpty(User.Statuses.data.First().message))
            {
                return (_height = _imageHeight + Style.PaddingTop);
            }

            width -= _imageWidth + (Style.PaddingLeft * 2) + Style.PaddingRight;
            _status = User.Statuses.data.First().message;
            _height = Style.TextFont.MeasureString(_status, new Rectangle(0, 0, width, 0)).Height + Style.PaddingBottom;


            if (_height < _imageHeight + Style.PaddingTop)
                _height = _imageHeight + Style.PaddingTop;

            _height += Style.PaddingBottom;
            return _height;
        }

        void StatusWrapperGetResults(object sender, TextEventArgs e)
        {
            User.Statuses.Parse(JObject.Parse(e.Text));
            User.Update();
        }

        public override void ResetHeight()
        {
            _height = -1;
        }

        public override void ItemPaint(Graphics g, int x, int y)
        {
            base.ItemPaint(g, x, y);
            int width = GetWidth(false);

            string url = _user.Picture.url + "&type=large";
            DrawImage(url, g, new Rectangle(Style.PaddingLeft, Style.PaddingTop, _imageWidth, _imageHeight));

            Color textColor = getCurrentFontColor(false);

            using (var p = new Pen(Color.DarkGray))
                g.DrawLine(p, 0, y + _height, width, y + _height);
            using (var b = new SolidBrush(textColor))
            {
                width -= _imageWidth + (Style.PaddingLeft * 2) + Style.PaddingRight;

                if (User == null || string.IsNullOrEmpty(_status))
                    g.DrawString(Settings.LocalizationStrings.noStatus, Style.TextFont, b,
                                 x + (Style.PaddingLeft * 2) + _imageWidth, y + Style.PaddingRight);
                else
                    g.DrawString(_status,
                                 new Rectangle(x + (Style.PaddingLeft * 2) + _imageWidth, y + Style.PaddingRight, width, 0),
                                 Style, textColor);
            }
        }

        public override XFItemClickResult GetClickResult()
        {
            switch (_selected)
            {
                case XFItemProfileHeadSelectedType.Status:
                    var input = new XFPanelTextInput();

                    input.Submitted += (o, e) =>
                                           {
                                               Cursor.Current = Cursors.WaitCursor;
                                               Application.DoEvents();

                                               var wrap = User.UpdateStatus(e.Text);
                                               string res = wrap.Post();
                                               if (!FBParseUtilities.HasError(res))
                                               {
                                                   ResetHeight();
                                               }

                                               Cursor.Current = Cursors.Default;
                                           };
                    Parent.SetRightPanel(input);
                    return XFItemClickResult.SlideLeft;
                case XFItemProfileHeadSelectedType.Picture:
                    FBAlbum album = User.Albums.data.FirstOrDefault(a => a.type == "profile");

                    if (album == null && User.Albums.data.Count == 0)
                    {
                        var wraper = User.Albums.Parse(User.id);
                        var data = wraper.Download();
                        User.Albums.Parse(JObject.Parse(data));
                        album = User.Albums.data.FirstOrDefault(a => a.type == "profile");
                    }

                    if (album == null)
                        return XFItemClickResult.Nothing;

                    var albumItem = new XFItemAlbum(album)
                                        {
                                            Visible = false
                                        };
                    ((XFPanelList)Parent).Add(albumItem);
                    return albumItem.GetClickResult();
            }

            return XFItemClickResult.Nothing;
        }

        public override void OnMouseDown(int x, int y)
        {
            base.OnMouseDown(x, y);
            if (x < (Style.PaddingLeft * 2) + _imageWidth)
                _selected = XFItemProfileHeadSelectedType.Picture;
            else
                _selected = XFItemProfileHeadSelectedType.Status;
        }

        public override void Dispose()
        {
            base.Dispose();
            _user.Updated -= _userUpdateEvent;

            if (_statusWrapper != null)
                _statusWrapper.Dispose();
        }
    }
}